package com.cwnu.sw.cys.core.user.dao;

import com.cwnu.sw.cys.core.common.domain.enums.IdempotentEnum;
import com.cwnu.sw.cys.core.common.domain.enums.YesOrNoEnum;
import com.cwnu.sw.cys.core.user.domain.entity.User;
import com.cwnu.sw.cys.core.user.domain.entity.UserBackpack;
import com.cwnu.sw.cys.core.user.mapper.UserBackpackMapper;
import com.cwnu.sw.cys.core.user.service.UserBackpackService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 用户背包表 服务实现类
 * </p>
 *
 * @author jisam
 * @since 2025-03-22
 */
@Service
public class UserBackpackDao extends ServiceImpl<UserBackpackMapper, UserBackpack> {

    public Integer getCountByValue(Long uid, Long id) {
        return lambdaQuery()
                .eq(UserBackpack::getId, uid)
                .eq(UserBackpack::getItemId, id)
                .eq(UserBackpack::getStatus, YesOrNoEnum.NO.getStatus())
                .count();
    }

    public void decrCountByValue(Long uid, Long id) {
        lambdaUpdate()
                .eq(UserBackpack::getId, uid)
                .eq(UserBackpack::getItemId, id)
                .eq(UserBackpack::getStatus, YesOrNoEnum.NO.getStatus())
                .set(UserBackpack::getStatus, YesOrNoEnum.YES.getStatus())
                .update();
    }

    public UserBackpack getFirstValidItem(Long uid, Long id) {
        return lambdaQuery()
                .eq(UserBackpack::getUid, uid)
                .eq(UserBackpack::getItemId, id)
                .eq(UserBackpack::getStatus, YesOrNoEnum.NO.getStatus())
                .orderByDesc(UserBackpack::getCreateTime)
                .last("limit 1")
                .one();
    }

    public boolean useItem(UserBackpack firstModifyCard) {
        return lambdaUpdate()
                .eq(UserBackpack::getId, firstModifyCard.getId())
                .eq(UserBackpack::getStatus, YesOrNoEnum.NO.getStatus())
                .set(UserBackpack::getStatus, YesOrNoEnum.YES.getStatus())
                .update();
    }

    public List<UserBackpack> getByItemId(Long uid, List<Long> badges) {
        return lambdaQuery()
                .eq(UserBackpack::getUid, uid)
                .eq(UserBackpack::getStatus, YesOrNoEnum.NO.getStatus())
                .in(UserBackpack::getItemId, badges)
                .list();
    }

    public UserBackpack getByIdempotent(String idempotentKey) {
        return lambdaQuery()
                .eq(UserBackpack::getIdempotent,idempotentKey)
                .one();
    }

    public List<UserBackpack> getByItemIds(List<Long> uidList, List<Long> itemIds) {
        return lambdaQuery()
                .in(UserBackpack::getUid, uidList)
                .in(UserBackpack::getItemId, itemIds)
                .eq(UserBackpack::getStatus, YesOrNoEnum.NO.getStatus())
                .list();
    }
}
